#include "pdeLut.h"
#include <fstream>
#include "bson_helper.h"
namespace pde {

	std::shared_ptr<Lut> Lut::New() {
		return std::make_shared<Lut>();

	}

	Lut::Lut() {

	}

	Lut::~Lut() {

	}

	std::string Lut::to_bson() {
		auto doc = document{};
		to_bson_vector("hu", hu_);
		to_bson_vector("rho", rho_);
		to_bson_vector("x0", x0_);
		to_bson_vector("wel", wel_);
		return std::string((char*)doc.view().data(), doc.view().length());
		return "";
	}

	bool Lut::from_bson(const std::string& bson_str) {
		auto bson = view(reinterpret_cast<const uint8_t*>(bson_str.c_str()), bson_str.length());
		from_bson_vector_int32("hu", hu_);
		from_bson_vector_double("rho", rho_);
		from_bson_vector_double("x0", x0_);
		from_bson_vector_double("wel", wel_);

		return true;
	}
	bool Lut::to_file(const std::string& fn) {
		std::ofstream ofile(fn, std::ios::binary);
		if (!ofile.good())
			return false; 
		auto& data = this->to_bson();

		ofile.write(data.c_str(), data.size());
		ofile.close();
		return true;
	}

	bool Lut::from_file(const std::string& fn) {

		std::ifstream infile(fn, std::ifstream::binary | std::ios::ate);
		if (infile.fail()) {
			return false;
		}
		std::string data;
		size_t size = infile.tellg();
		infile.seekg(0);
		data.resize(size);
		infile.read(&data[0], size);
		infile.close();

		return this->from_bson(data);
	}

}